<template>
    <div class="image-upload-box clearfix">
        <form :id="id">
            <input type="file" name="file" :id="id+'fileInput'" class="hiddenFileInput" @change="upload">
            <input name="accept" type="hidden" />
        </form>
        <el-button size="mini" round @click="uploadBefore" class="imageUploadButton">上传</el-button>
        <img v-if="imgPath.length != 0" :src="imgPath" class="img">
        <div v-else class="img"></div>
    </div>
</template>

<script>
import uuid from 'uuid/v4'
import fileApi from '../../api/file'
export default {
    name:'image-upload',
    data(){return {
        id:uuid(),
        key:uuid(),
        upToken:'',
    }},
    props:['imgPath'],
    mounted:function(){
        this.path = this.imgPath
    },
    methods:{
        uploadBefore:function(){
            const _this = this;
            //触发file INPUT的点击事件
            document.getElementById(_this.id+'fileInput').click()
        },
        
        upload:function(){
            const _this = this
            //get token
            fileApi.getUpToken()
                .then(function(data){
                    if(data.length > 0){
                        var token = data;
                        //get key
                        var key = uuid()
                        //get formData
                        var formData = new FormData(document.getElementById(_this.id));
                        
                        fileApi.upload(formData,token,key,null)
                            .then(function(data){
                                if(data.key){
                                    var path = fileApi.getDownloadURL(data.key)
                                    _this.$emit('success',path)
                                }
                            })
                    }
                })

        }
    }
}
</script>

<style>
.image-upload-box *{
    float: left;
}
.hiddenFileInput{
    display: none
}
.imageUploadButton{
    border-radius: 10px;
    margin-top: 7px;
}
.image-upload-box .img{
    height: 100px;
}
.img{
    margin-left: 20px;
    border: 1px solid black;
}
</style>
